﻿using System;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Forum.Controls.Base;
using Eneta.Portal.Forum.Controls.Common;
using Eneta.Portal.Forum.Core.Domain.Entities;
using Eneta.Portal.Forum.Core.Service.Application;
using FredCK.FCKeditorV2;
using Microsoft.SharePoint;

namespace Eneta.Portal.Forum.Controls
{
    public class UpdateMessageControl : BaseForumControl
    {
        protected Label _postModeTitle;
        protected TextBox _subjectField;
        protected FCKeditor _bodyField;
        protected LinkButton _saveButton;
        protected LinkButton _cancelButton;
        protected Repeater _messagesRepeater;
        protected Label _previewTitleLabel;
        protected HtmlTableRow _titleRow;

        protected HtmlAnchor _categoryLink;
        protected HtmlAnchor _forumLink;
        protected HtmlAnchor _topicLink;

        protected HtmlTableRow _explanationRow;
        protected TextBox _explanationField;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            WebPartParent = (EnetaForumWebPart)Parent;
            _saveButton.Click += SaveButtonClick;
            _cancelButton.Click += CancelButtonClick;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (SPContext.Current.Web.CurrentUser == null)
            {
                Page.Response.Redirect("/_layouts/Eneta.Portal.Authentication/LiveAuthHandler.aspx?action=login&ReturnUrl=" + HttpUtility.UrlEncode(Page.Request.RawUrl));                
                return;
            }


            var forumRep = new ForumRepository(SPContext.Current.Web);
            int postId;
            ForumPostDto post = null;
            if (int.TryParse(HttpContext.Current.Request["post"], out postId))
            {
                post = forumRep.GetForumPostById(postId);
            }

            _explanationRow.Visible = false;
            if (MessageMode == PostMode.Edit)
            {
                if (post == null)
                {
                    Response.Redirect("/foorum/");
                    return;
                }
                if (!SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                {
                    if (SPContext.Current.Web.CurrentUser.LoginName != post.AuthorUserName)
                    {
                        Response.Redirect("/foorum/");
                        return;
                    }
                }
                else
                {
                    _explanationRow.Visible = true;
                }
            }
            var category = forumRep.GetForumCategoryById(_categoryID);
            _categoryLink.HRef = string.Format(_categoryLink.HRef, _categoryID);
            if (category != null)
            {
                _categoryLink.InnerText = category.Title;
            }
            else
            {
                _categoryLink.InnerText = "Unknown";
            }

            var forum = forumRep.GetForumById(_forumID);
            _forumLink.HRef = string.Format(_forumLink.HRef, _forumID);
            if (forum != null)
            {
                _forumLink.InnerText = forum.Title;
            }
            else
            {
                _forumLink.InnerText = "Unknown";
            }

            if(MessageMode == PostMode.Edit || MessageMode == PostMode.Reply)
            {
                _subjectField.Visible = false;
                _titleRow.Visible = false;

                var topic = forumRep.GetForumTopicById(_topicID);
                _topicLink.HRef = string.Format(_topicLink.HRef, _topicID);

                if (topic != null)
                {
                    _topicLink.InnerText = topic.Title;
                }
                else
                {
                    _topicLink.InnerText = "Unknown";
                }
            }
            else
            {
                _previewTitleLabel.Text = "Uus teema";
                _topicLink.HRef = string.Empty;
                _topicLink.InnerText = "Uus teema";
            }
            

            if (MessageMode != PostMode.Edit)
            {
                ForumPostDto[] ds = null;
                if (int.TryParse(HttpContext.Current.Request["post"], out postId))
                {                    
                    _previewTitleLabel.Text = post.Title;
                    ds = new[] {post};
                }
                if (ds == null)
                {
                    if (_topicID > 0)
                    {
                        var topic = forumRep.GetForumTopicById(_topicID);
                        _previewTitleLabel.Text = topic.Title;
                        ds = new[] {topic.Starter};
                    }
                }
                _messagesRepeater.DataSource = ds;
                _messagesRepeater.DataBind();

                if (!IsPostBack)
                    if (!string.IsNullOrEmpty(Request.QueryString["quote"]))
                    {
                        //_bodyField.Value = "<p>[quote]" + RegExHelper.RemoveHtmlTags(ds[0].Body.Replace("</p>","\r\n")).Replace("\r\n","<br/><br/>") +"[/quote]</p><p>&nbsp;</p>";
                        _bodyField.Value = "[quote name=&quot;" + ds[0].AuthorProfileName + "&quot;]" + ds[0].Body + "[/quote]<p></p>";
                    }
            }

            if(MessageMode == PostMode.Edit && !IsPostBack)
            {
                if(post != null)
                {
                    _previewTitleLabel.Text = post.Title;
                    _bodyField.Value = post.Body;
                    _saveButton.Text = "Salvesta";
                }
            }

            if(MessageMode == PostMode.Reply || !string.IsNullOrEmpty(Request.QueryString["post"]))
            {
                _titleRow.Visible = false;
                _messagesRepeater.Visible = true;
            }
            else
            {
                _titleRow.Visible = true;
                _messagesRepeater.Visible = false;
                _previewTitleLabel.Visible = false;
            }

            Page.Title = "Foorum > " + _previewTitleLabel.Text + " | Microsoft Eneta";

            var master = Page.Master;
            if (master != null)
            {                
                var typedMaster = master as MasterBaseWithDesignHack;
                if (typedMaster != null)
                {
                    var dto = new RssLinksDto();
                    if (forum != null)
                    {
                        dto.RssUrl = forum.FeedBurnerUrl;
                        if (string.IsNullOrEmpty(dto.RssUrl))
                            dto.RssUrl = "/foorum/Lehed/default.aspx?control=ViewTopics&rss=1&forum=" + forum.Id;
                        dto.RssTitle = forum.Title;
                        typedMaster.SetRssLinks(dto);
                    }
                }
            }
        }

        

        private void CancelButtonClick(object sender, EventArgs e)
        {
            if (_topicID != 0)
                Response.Redirect("/foorum/Lehed/default.aspx?control=ViewMessages&topic=" + _topicID);
            else if (_forumID != 0)
                Response.Redirect("/foorum/Lehed/default.aspx?control=ViewTopics&forum=" + _forumID);
            else
                Response.Redirect("/foorum/");
            Response.End();
        }

        private void SaveButtonClick(object sender, EventArgs e)
        {
            if (SPContext.Current.Web.CurrentUser == null)
            {
                HttpContext.Current.Response.Redirect("/foorum/", false);
                return;
            }

            Topic parentTopic;
            var listItemId = 0;

            if (MessageMode == PostMode.Edit)
            {
                parentTopic = RepositoryRegistry.TopicRepository.GetById(_topicID);
                int.TryParse(Request.QueryString["post"], out listItemId);
            }
            else if (MessageMode == PostMode.New)
            {
                parentTopic = new Topic(_forumID, _subjectField.Text);
                parentTopic.LastPost = DateTime.Now;
                parentTopic.TopicStarterId = ForumApplication.Instance.SpUser.ID;
                _topicID = RepositoryRegistry.TopicRepository.Save(parentTopic);
                WebPartParent.TopicCount++;
            }
            else
            {
                parentTopic = RepositoryRegistry.TopicRepository.GetById(_topicID);
            }

            string messageTitle;
            if(MessageMode == PostMode.New)
                messageTitle = _subjectField.Text;
            else
                messageTitle = string.Format("RE: {0}", parentTopic.Name);

            var message = new Message(_topicID);
            message.Name = HttpUtility.HtmlEncode(messageTitle);
            message.Id = listItemId;
            //message.Body = HttpUtility.HtmlEncode(_txtBody.Text).Replace("\n", "<br/>");
            //message.Body = HttpUtility.HtmlEncode(_txtBody.Value).Replace("\n", "<br/>");
            //var body = _bodyField.Value.Replace("<p>[quote]</p>\r\n<p>", "<p>[quote]");
            //body = body.Replace("</p>\r\n<p>[/quote]</p>","[/quote]</p>");
            message.Body = RegExHelper.RemoveForbiddenAttributes(_bodyField.Value);
            message.UserId = ForumApplication.Instance.SpUser.ID;
            message.Author = ForumApplication.Instance.CurrentUser;
            message.ForumId = parentTopic.ForumId;

            var post = new ForumPostDto();
            post.AuthorUserName = ForumApplication.Instance.SpUser.LoginName;
            post.Body = message.Body;
            post.ForumId = parentTopic.ForumId;
            post.Title = messageTitle;
            post.TopicId = _topicID;
            post.Id = listItemId;
            if(SPContext.Current.Web.CurrentUser != null)
                if(SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                {
                    post.EditorExplanation = _explanationField.Text;
                }

            if(MessageMode == PostMode.Edit)
            {
                post.ModifiedBy = SPContext.Current.Web.CurrentUser.Name;
                post.ModifiedByUserName = SPContext.Current.Web.CurrentUser.LoginName;
            }

            var forumrep = new ForumRepository(SPContext.Current.Web);
            forumrep.SaveForumPost(post);

            //RepositoryRegistry.MessageRepository.Save(message);

            if (MessageMode != PostMode.Edit)
            {
                // Increase the post count in the main web part
                WebPartParent.PostCount++;
                WebPartParent.PersistProperties();

                // Increase the number of posts for this user
                message.Author.NumPosts++;
                RepositoryRegistry.ForumUserRepository.Save(message.Author);
            }
            // Redirect to the new post
            var url = ForumApplication.Instance.GetLink(SharePointForumControls.ViewMessages, "topic={0}", _topicID);
            Page.Response.Redirect(url);
        }
    }
}
